package net.uman.framework.modules.objectpool;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.uman.framework.modules.security.springsecurity.SpringSecurityUtils;

import org.apache.commons.lang.StringUtils;

public class ObjectPoolLogger {
	PrintWriter writer = null;
	boolean enable;
	
	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}

	public void setLogFile(String logFile) {
		if (StringUtils.isNotEmpty(logFile)) {
			File file = new File(logFile);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			try {
				writer = new PrintWriter(new FileOutputStream(file, true));	// append content
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void writeHitLog(String key) {
		writeLog(key, true);
	}
	
	public void writeMissedLog(String key) {
		writeLog(key, false);
	}
	
	private void writeLog(String key, boolean hit) {
		if (!enable || writer == null) {
			return;
		}
		
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
		
		String user = SpringSecurityUtils.getCurrentUserName();
		StringBuffer sb = new StringBuffer();
		sb.append(fmt.format(new Date())).append(",");
		sb.append(StringUtils.isBlank(user)? "<unknown>" : user).append(",");
		sb.append(hit ? "hit" : "missed").append(",");
		sb.append(key);
		
		writer.println(sb.toString());
		writer.flush();
	}	
}
